<template>
  <div class="latest-users">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>最新用户</span>
          <el-button text @click="refreshUsers">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </template>
      
      <div v-loading="loading" class="users-list">
        <div
          v-for="user in latestUsers"
          :key="user.id"
          class="user-item"
        >
          <el-avatar :size="40" :src="user.userAvatar">
            {{ user.userName?.charAt(0)?.toUpperCase() || 'U' }}
          </el-avatar>
          <div class="user-info">
            <div class="user-name">{{ user.userName || user.userAccount }}</div>
            <div class="user-time">{{ formatTime(user.createTime) }}</div>
          </div>
          <el-tag 
            :type="user.userRole === 0 ? 'danger' : 'success'" 
            size="small"
          >
            {{ user.userRole === 0 ? '管理员' : '用户' }}
          </el-tag>
        </div>
        
        <div v-if="latestUsers.length === 0 && !loading" class="empty-state">
          <el-empty description="暂无用户数据" />
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'
import dayjs from 'dayjs'

const userStore = useUserStore()
const latestUsers = ref<any[]>([])
const loading = ref(false)

// 格式化时间
const formatTime = (time: string) => {
  return dayjs(time).format('MM-DD HH:mm')
}

// 获取最新用户
const loadLatestUsers = async () => {
  try {
    loading.value = true
    const users = await userStore.getLatestUsers(4)
    latestUsers.value = users
  } catch (error) {
    console.error('获取最新用户失败:', error)
    ElMessage.error('获取最新用户失败')
  } finally {
    loading.value = false
  }
}

// 刷新用户列表
const refreshUsers = () => {
  loadLatestUsers()
}

// 组件挂载时加载数据
onMounted(() => {
  loadLatestUsers()
})
</script>

<style scoped>
.latest-users {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.users-list {
  min-height: 200px;
}

.user-item {
  display: flex;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.user-item:last-child {
  border-bottom: none;
}

.user-info {
  flex: 1;
  margin-left: 12px;
}

.user-name {
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
}

.user-time {
  font-size: 12px;
  color: #909399;
}

.empty-state {
  padding: 40px 0;
  text-align: center;
}
</style> 